package com.lihao.sam.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @Author Qinheyun
 * @Description: 过滤器
 */

@WebFilter("/*")
public class UserFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1.验证当前Session是否存在用户
        HttpServletRequest req= (HttpServletRequest) request;
        //2.验证是否需要过滤
        String url=req.getRequestURI();
        if(url.contains(".css") || url.contains(".js") || url.contains("login.html")
                ||url.contains("login.do") || url.contains("createcode.do")){
            //放行
            chain.doFilter(request, response);
        }else {
            if(req.getSession().getAttribute("user")==null){
                //3.未登录
                HttpServletResponse resp= (HttpServletResponse) response;
                resp.sendRedirect("/login.html");
            }else {
                //4.已登录 放行
                chain.doFilter(request, response);
            }
        }
    }
}
